<template lang="html">
  <div v-loading="loading" class="order-panel">
    <div class="main-top-panel">
      <el-row>
        <el-col :span="24">
          <el-form
            ref="searchFormRef"
            :model="orderSearchForm"
            :inline="true"
            label-width="140px"
            size="small"
          >
            <el-form-item label="订单号" prop="nb">
              <el-input
                v-model="orderSearchForm.nb"
                type="text"
                clearable
                placeholder="订单号"
              />
            </el-form-item>
            <el-form-item label="快递发货单号" prop="package_nb">
              <el-input
                v-model="orderSearchForm.package_nb"
                type="text"
                clearable
                placeholder="快递发货单号"
              />
            </el-form-item>
            <el-form-item label="收货人姓名" prop="receiver_name">
              <el-input
                v-model="orderSearchForm.receiver_name"
                type="text"
                clearable
                placeholder="收货人姓名"
              />
            </el-form-item>
            <el-form-item label="收货人电话" prop="receiver_mobile_number">
              <el-input
                v-model="orderSearchForm.receiver_mobile_number"
                type="text"
                clearable
                placeholder="收货人电话"
              />
            </el-form-item>
            <el-form-item label="订单状态" prop="status">
              <el-select v-model="orderSearchForm.status">
                <el-option
                  v-for="item in [{
                    value: undefined,
                    label: '不限'
                  },{
                    value: 1,
                    label: '待付款'
                  },{
                    value: 2,
                    label: '待发货'
                  }, {
                    value: 3,
                    label: '待签收'
                  }, {
                    value: 4,
                    label: '待完成'
                  }, {
                    value: 5,
                    label: '待完成'
                  }, {
                    value: 100,
                    label: '已完成'
                  }, {
                    value: 110,
                    label: '已取消'
                  }, {
                    value: 120,
                    label: '已退款'
                  }]"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-row>
              <el-col :span="24">
                <el-form-item label="订单下单(创建)时间" prop="create_time">
                  <el-date-picker
                    v-model="orderSearchForm.create_time"
                    type="datetimerange"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    :picker-options="payTimestampPickerOptions"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    align="right"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="订单支付时间" prop="pay_time">
                  <el-date-picker
                    v-model="orderSearchForm.pay_time"
                    type="datetimerange"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    :picker-options="payTimestampPickerOptions"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    align="right"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-button size="small" type="primary" icon="el-icon-search"
                       @click="getOrderList(orderTableDataPaginateCurrentPage,orderTableDataPaginateTotalPageSize)">搜索
            </el-button>
            <el-button type="primary" size="small" @click="seaWaybillDialog('post')">导入订单</el-button>
          </el-form>
        </el-col>
        <el-col :span="2"/>
      </el-row>
    </div>
    <el-button type="primary" @click="orderDialog('post')">添加</el-button>
    <el-dialog v-loading="loading" title="编辑" :visible.sync="orderDiaIsShow" class="diaForm" :append-to-body="false">
      <el-form
        ref="orderRef"
        :model="orderForm"
        :rules="orderRules"
        label-width="140px"
      >
        <el-form-item label="车牌号" prop="plate_number">
          <el-col :span="15">
            <el-input
              v-model="orderForm.plate_number"
              type="text"
              placeholder="请输入车牌号"
            />
          </el-col>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="editOrder()"
          >确认
          </el-button>
          <el-button @click="orderDiaIsShow = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      v-loading="loading"
      title="商品发货"
      :visible.sync="orderFhDiaIsShow"
      class="diaForm"
      :append-to-body="false">
      <el-form
        ref="orderFhRef"
        :model="orderFhForm"
        :rules="orderFhRules"
        label-width="140px"
      >
        <el-form-item label="商品规格">
          <el-col :span="15">
            <el-checkbox-group v-model="list_ids" @change="selectOrderList">
              <el-checkbox
                v-for="item in orderFhForm.orderListInfo"
                :key="item.id"
                :label="item.id"
                :disabled="item.extend_status_text === '已退款'||(item.package_nb !== '' && item.package_nb !== null && item.package_nb !== undefined)"
              >{{item.product_sku_name}}{{item.extend_status_text === '已退款' ? '(已退款)' : ''}}
              </el-checkbox>
            </el-checkbox-group>
          </el-col>
        </el-form-item>
        <el-form-item label="收货人" prop="receiver_name">
          <el-col :span="15">
            <el-input
              v-model="orderFhForm.receiver_name"
              type="text"
              placeholder="收货人"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="收货人手机号码" prop="receiver_mobile_number">
          <el-col :span="15">
            <el-input
              v-model="orderFhForm.receiver_mobile_number"
              type="text"
              placeholder="收货人手机号码"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="收货地址" prop="receiver_address">
          <el-col :span="15">
            <el-input
              v-model="orderFhForm.receiver_address"
              type="text"
              placeholder="收货地址"
            />
          </el-col>
        </el-form-item>
        <hr>
        <el-form-item label="快递公司" prop="package_company_id">
          <el-col :span="15">
            <el-select
              v-model="orderFhForm.package_company_id"
              filterable
              remote
              reserve-keyword
              placeholder="快递公司"
              :remote-method="getPackageCompanyRemote"
              :loading="loading"
            >
              <el-option
                v-for="item in packageCompanyOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="快递单号" prop="package_nb">
          <el-col :span="15">
            <el-input
              v-model="orderFhForm.package_nb"
              type="text"
              placeholder="快递单号"
            />
          </el-col>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="editOrder()"
          >确认
          </el-button>
          <el-button @click="orderFhDiaIsShow = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      v-loading="loading"
      title="订单发货"
      :visible.sync="orderCancelDiaIsShow"
      class="diaForm"
      size="mini"
      :append-to-body="false">
      <el-form
        ref="orderCancelRef"
        :model="orderCancelForm"
        :rules="orderCancelRules"
        label-width="140px"
      >
        <el-form-item label="订单取消原因" prop="cancel_desc">
          <el-col :span="15">
            <el-input
              v-model="orderCancelForm.cancel_desc"
              type="text"
              placeholder="订单取消原因"
            />
          </el-col>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="editOrder()"
          >确认
          </el-button>
          <el-button @click="orderCancelDiaIsShow = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-table
      :data="orderTableData"
      border
      style="width: 100%"
    >
      <el-table-column
        label="会员信息"
      >
        <template slot-scope="scope">
          <el-row>
            <el-col :span="24">
              上级昵称:
            </el-col>
            <el-col :span="24">
              上级手机:
            </el-col>
            <el-col :span="24">
              会员昵称: {{ scope.row.userInfo.nickname }}
            </el-col>
            <el-col :span="24">
              会员手机: {{ scope.row.userInfo.mobile_number }}
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column
        label="订单信息"
        width="300"
      >
        <template slot-scope="scope">
          <el-row>
            <el-col :span="24">
              付款金额：￥{{ scope.row.price_pay }}
            </el-col>
            <el-col :span="24">
              总金额：￥{{ scope.row.price_total }}
            </el-col>
            <el-col :span="24">
              优惠总金额：￥{{ scope.row.price_discount }}
            </el-col>
            <el-col :span="24">
              优惠说明：
              <span v-for="(item) in  scope.row.price_discount_desc ">
                <span v-for="key in Object.keys(item)">
                  {{key + ':' + item[key]}}
                </span>
              </span>
            </el-col>
            <el-col :span="24">
              状态：
              <el-tag type="danger" size="mini">{{ scope.row.extend_status_text }}</el-tag>
            </el-col>
            <el-col :span="24">
              单号：{{ scope.row.nb }}
            </el-col>
            <el-col :span="24">
              描述：{{ scope.row.remark }}
            </el-col>
            <el-col :span="24">
              下单时间：{{ scope.row.create_time }}
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column
        label="支付信息"
        width="310"
      >
        <template slot-scope="scope">
          <el-row>
            <el-col v-if="scope.row.pay_type" :span="24">
              收款类型：{{ scope.row.pay_type }}
            </el-col>
            <el-col v-if="scope.row.price" :span="24">
              支付金额：￥{{ scope.row.price }}
            </el-col>
            <el-col :span="24">
              支付单号：{{ scope.row.pay_nb }}
            </el-col>
            <el-col :span="24">
              支付时间：{{ scope.row.pay_time }}
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column
        label="收货信息"
      >
        <template slot-scope="scope">
          <el-row>
            <el-col :span="24">
              收货地址：
            </el-col>
            <el-col :span="24">
              {{ scope.row.receiver_name }}{{ scope.row.receiver_mobile_number }}
            </el-col>
            <el-col :span="24">
              {{ scope.row.receiver_address }}
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column
        label="发货信息"
      >
        <template slot-scope="scope">
          <div v-for="item in scope.row.orderListInfo" style="border: 1px solid #00ff80;margin-bottom: 5px;padding:2px">
            <el-row>
              <el-col :span="24">
                <el-tag size="small">{{ item.extend_status_text }}</el-tag>
              </el-col>
              <el-col :span="24">
                规格：{{ item.product_sku_name }}
              </el-col>
              <el-col v-if="item.packageCompanyInfo" :span="24">
                快递公司：{{ item.packageCompanyInfo.name }}
              </el-col>
              <el-col v-if="item.package_nb" :span="24">
                快递单号：{{ item.package_nb }}
                <el-tag size="small" type="success">已发货</el-tag>
              </el-col>
              <el-col :span="24">
                快递费用：
                <span v-if="item.price_package === '0' || item.price_package === '0.00'">包邮</span>
                <span v-else>{{item.price_package}}</span>
              </el-col>
              <el-col v-if="item.package_fh_time" :span="24">
                发货时间：{{ item.package_fh_time }}
              </el-col>
            </el-row>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="商品信息"
      >
        <template slot-scope="scope">
          <el-row>
            <el-col :span="24">
              <img :src="scope.row.product_logo_url" alt="" width="100">
            </el-col>
            <el-col :span="24">
              {{ scope.row.product_name }}
            </el-col>
            <el-col v-for="item in scope.row.orderListInfo" :span="24">
              规格:{{ item.product_sku_name }} x {{ item.count_total }}
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        label="操作"
        width="300"
        align="center"
      >
        <template slot-scope="scope">
          <el-col :span="24">
            <el-button v-if="scope.row.extend_status_text === '待付款'" type="text" size="small"
                       @click="orderDialog('cancel',scope.row)">取消订单
            </el-button>
          </el-col>
          <el-col :span="24">
            <el-button v-if="scope.row.extend_status_text === '待发货'" type="text" size="small"
                       @click="orderDialog('fh',scope.row)">
              填写发货内容并发货
            </el-button>
          </el-col>
          <el-col :span="24">
            <el-button v-if="scope.row.extend_status_text === '退款待审核'" type="text" size="small"
                       @click="orderDialog('refundConfirm',scope.row)">关闭订单并退款给用户
            </el-button>
            <el-button v-if="scope.row.extend_status_text === '待发货'" type="text" size="small"
                       @click="orderDialog('refundConfirm',scope.row)">关闭订单并退款给用户
            </el-button>
          </el-col>
        </template>
      </el-table-column>
    </el-table>
    <div style="text-align:center;margin-top:20px">
      <el-pagination
        :current-page="orderTableDataPaginateCurrentPage"
        :page-sizes="orderTableDataPaginateTotalPageSizes"
        :page-size="orderTableDataPaginateTotalPageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="orderTableDataPaginateTotal"
        @size-change="orderTableDataHandleSizeChange"
        @current-change="orderTableDataHandleCurrentChange"
      >
        <!-- <span>当前{{ orderTableDataPaginateCurrentPage }}页，</span>
                        <span>共{{ orderTableDataPaginateLastPage }}页</span> -->
      </el-pagination>
    </div>
  </div>
</template>

<script>
import moment from 'moment'

export default {
  data() {
    return {
      loading: false,
      orderSearchForm: {
        nb: undefined,
        package_nb: undefined,
        receiver_name: undefined,
        receiver_mobile_number: undefined,
        create_time: undefined,
        pay_time: undefined,
        status: undefined
      },
      packageCompanySearchForm: {},
      orderRefundConfirmForm: {},
      packageCompanyOptions: [],
      orderTableData: [],
      orderTableDataPaginateCurrentPage: 1,
      orderTableDataPaginateTotal: 1,
      orderTableDataPaginateLastPage: 1,
      orderTableDataPaginateTotalPageSize: 10,
      orderTableDataPaginateTotalPageSizes: [10, 20, 50, 100],
      orderTab: [],
      orderEditType: 'post',
      orderDiaIsShow: false,
      orderFhDiaIsShow: false,
      orderCancelDiaIsShow: false,
      orderForm: {},
      orderRules: {
        mobile_number: [{
          required: true,
          trigger: 'blur'
        }],
        password: [{
          required: true,
          trigger: 'blur'
        }]
      },
      orderFhForm: {},
      list_ids: [],
      orderFhRules: {
        receiver_name: [{
          required: true,
          trigger: 'blur'
        }],
        receiver_mobile_number: [{
          required: true,
          trigger: 'blur'
        }],
        receiver_address: [{
          required: true,
          trigger: 'blur'
        }],
        package_company_id: [{
          required: true,
          trigger: 'blur'
        }],
        package_nb: [{
          required: true,
          trigger: 'blur'
        }]
      },
      orderCancelForm: {},
      orderCancelRules: {
        id: [{
          required: true,
          trigger: 'blur'
        }],
        cancel_desc: [{
          required: true,
          trigger: 'blur'
        }]
      },
      payTimestampPickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            const start = moment().day(moment().day()).startOf('day').valueOf()
            const end = moment().day(moment().day()).endOf('day').valueOf()
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一周',
          onClick(picker) {
            const start = moment().week(moment().week()).startOf('week').valueOf() // 这样是年月日的格式
            const end = moment().week(moment().week()).endOf('week').valueOf() // 这样是时间戳的格式
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const start = moment().month(moment().month()).startOf('month').valueOf()
            const end = moment().month(moment().month()).endOf('month').valueOf()
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const start = moment().month(moment().month() - 2).startOf('month').valueOf()
            const end = moment().month(moment().month()).endOf('month').valueOf()
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '今年',
          onClick(picker) {
            const start = moment().year(moment().year()).startOf('year').valueOf()
            const end = moment().year(moment().year()).endOf('year').valueOf()
            picker.$emit('pick', [start, end])
          }
        }]
      }
      // payTimestampPickerOptions: {
      //   shortcuts: [{
      //     text: '今天',
      //     onClick(picker) {
      //       picker.$emit('pick', new Date())
      //     }
      //   }, {
      //     text: '明天',
      //     onClick(picker) {
      //       const date = new Date()
      //       date.setTime(date.getTime() + 3600 * 1000 * 24)
      //       picker.$emit('pick', date)
      //     }
      //   }, {
      //     text: '后天',
      //     onClick(picker) {
      //       const date = new Date()
      //       date.setTime(date.getTime() + 3600 * 1000 * 24 * 2)
      //       picker.$emit('pick', date)
      //     }
      //   }, {
      //     text: '一周后',
      //     onClick(picker) {
      //       const date = new Date()
      //       date.setTime(date.getTime() + 3600 * 1000 * 24 * 7)
      //       picker.$emit('pick', date)
      //     }
      //   }]
      // }
    }
  },
  created() {
    this.getOrderList()
    this.getPackageCompanyList(1, 100000)
  },
  methods: {
    orderTableDataHandleSizeChange(val) {
      // 改变每页显示的条数
      this.orderTableDataPaginateTotalPageSize = val
      this.getOrderList(1, this.orderTableDataPaginateTotalPageSize)
    },
    selectOrderList(val) {
      console.log('selectOrderList', val)
      this.list_ids = val
    },
    orderTableDataHandleCurrentChange(val) {
      this.orderTableDataPaginateCurrentPage = val
      this.getOrderList(val, this.orderTableDataPaginateTotalPageSize)
    },
    getOrderList(page = 1, limit = 10) {
      this.loading = true
      this.orderSearchForm.page = page
      this.orderSearchForm.limit = limit
      console.log(this.orderSearchForm)
      if (!this.orderSearchForm.status) {
        this.orderSearchForm.status = undefined
      }
      if (!this.orderSearchForm.nb) {
        this.orderSearchForm.nb = undefined
      }
      if (this.orderSearchForm.package_nb === '') {
        this.orderSearchForm.package_nb = undefined
      }
      if (this.orderSearchForm.receiver_name === '') {
        this.orderSearchForm.receiver_name = undefined
      }
      if (this.orderSearchForm.receiver_mobile_number === '') {
        this.orderSearchForm.receiver_mobile_number = undefined
      }
      if (this.orderSearchForm.create_time === null) {
        this.orderSearchForm.create_time = undefined
      }
      if (this.orderSearchForm.pay_time === null) {
        this.orderSearchForm.pay_time = undefined
      }
      this.$store.dispatch('order/getOrderList', this.orderSearchForm).then((res) => {
        this.orderTableData = res.data.data
        this.orderTableDataPaginateTotal = res.data.total
        this.orderTableDataPaginateCurrentPage = res.data.current_page
        this.orderTableDataPaginateLastPage = res.data.last_page
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    getPackageCompanyRemote(query) {
      if (query !== '') {
        this.packageCompanyOptions = this.packageCompanyTableData.filter(item => {
          return item.name
            .indexOf(query) > -1
        })
      } else {
        this.packageCompanyOptions = this.packageCompanyTableData
      }
    },
    getPackageCompanyList(page = 1, limit = 10) {
      this.loading = true
      this.packageCompanySearchForm.page = page
      this.packageCompanySearchForm.limit = limit
      this.$store.dispatch('packages/getPackageCompanyList', this.packageCompanySearchForm).then((res) => {
        this.packageCompanyTableData = res.data
        this.packageCompanyOptions = res.data
        this.packageCompanyTableDataPaginateTotal = res.data.total
        this.packageCompanyTableDataPaginateCurrentPage = res.data.current_page
        this.packageCompanyTableDataPaginateLastPage = res.data.last_page
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    deleteOrder(row) {
      // console.log(row)
      this.$confirm('确认删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.loading = true
          this.$store.dispatch('order/deleteOrder', { id: row.id }).then((res) => {
            this.getOrderList()
            this.loading = false
            this.orderDiaIsShow = false
            this.$message({
              type: 'success',
              message: res.msg
            })
          }).catch(() => {
            // this.loading = false
            return false
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    editOrder() {
      switch (this.orderEditType) {
        case 'post':
          this.$refs['orderRef'].validate((valid) => {
            if (valid) {
              this.loading = true
              this.$store.dispatch('order/postOrder', this.orderForm).then((res) => {
                this.getOrderList()
                this.orderForm = {}
                this.loading = false
                this.orderDiaIsShow = false
                this.$message({
                  type: 'success',
                  message: res.msg
                })
              }).catch(() => {
                this.loading = false
              })
            } else {
              return false
            }
          })
          break
        case 'put':
          this.$refs['orderRef'].validate((valid) => {
            if (valid) {
              this.loading = true
              this.$store.dispatch('order/putOrder', this.orderForm).then((res) => {
                this.getOrderList()
                this.orderForm = {}
                this.loading = false
                this.orderDiaIsShow = false
                this.$message({
                  type: 'success',
                  message: res.msg
                })
              }).catch(() => {
                this.loading = false
              })
            } else {
              return false
            }
          })
          break
        case 'fh':
          this.$refs['orderFhRef'].validate((valid) => {
            if (valid) {
              this.loading = true
              console.log(this.orderFhForm)
              console.log(this.list_ids.length)
              if (this.list_ids.length <= 0) {
                this.$message({
                  type: 'error',
                  message: '请选择商品规格'
                })
                this.loading = false
                return
              }
              console.log('ok')
              this.orderFhForm.list_ids = this.list_ids
              this.$store.dispatch('order/putOrderFh', this.orderFhForm).then((res) => {
                this.getOrderList()
                this.orderFhForm = {}
                this.loading = false
                this.orderFhDiaIsShow = false
                this.$message({
                  type: 'success',
                  message: res.msg
                })
              }).catch(() => {
                this.loading = false
              })
            } else {
              return false
            }
          })
          break
        case 'cancel':
          this.$refs['orderCancelRef'].validate((valid) => {
            if (valid) {
              this.loading = true
              console.log(this.orderFhForm)
              this.$store.dispatch('order/putOrderCancel', this.orderCancelForm).then((res) => {
                this.getOrderList()
                this.orderCancelForm = {}
                this.loading = false
                this.orderCancelDiaIsShow = false
                this.$message({
                  type: 'success',
                  message: res.msg
                })
              }).catch(() => {
                this.loading = false
              })
            } else {
              return false
            }
          })
          break
        case 'refundConfirm':
          this.loading = true
          console.log(this.orderRefundConfirmForm)
          this.$store.dispatch('order/putOrderRefundConfirm', this.orderRefundConfirmForm).then((res) => {
            this.getOrderList()
            this.orderRefundConfirmForm = {}
            this.loading = false
            this.$message({
              type: 'success',
              message: res.msg
            })
          }).catch(() => {
            this.loading = false
          })
          break
      }
    },
    orderDialog(type, row) {
      switch (type) {
        case 'post':
          this.orderDiaIsShow = true
          this.orderEditType = 'post'
          break
        case 'put':
          this.orderDiaIsShow = true
          this.orderEditType = 'put'
          // 这里一定要使用nextTick的方式赋值，不然会卡住input
          this.$nextTick(() => {
            //   this.$set(this.orderForm, 'id', row.id)
          })
          break
        case 'fh':
          this.orderFhDiaIsShow = true
          this.orderEditType = 'fh'
          this.orderFhForm = row
          this.list_ids = []
          console.log(this.orderFhForm)
          break
        case 'cancel':
          this.orderCancelDiaIsShow = true
          this.orderEditType = 'cancel'
          this.orderCancelForm = row
          break
        case 'refundConfirm':
          this.orderEditType = 'refundConfirm'
          this.orderRefundConfirmForm.id = row.id
          this.editOrder()
          break
        default:
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.order-panel {
  padding: 18px;
  font-size: 10px;
}
</style>
